<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '充值',
  },
}
</route>

<template>
  <scroll-view 
    :scroll-y="true"
    style="height: 100%;"
    @scrolltolower="onRefresh"
    :class="[themeConfig.theme === 'dark' ? 'recharge-dark-bg' : 'recharge-container']" 
  >
    <view class="w-750rpx m-a pt-32rpx bg-white"
      :class="[{ 'dark-color': themeConfig.theme === 'dark' }]"
    >
      <view class="box-border pl-58rpx color-#2E1305"
        :class="[{ '!color-white': themeConfig.theme === 'dark' }]"
      >
        <text class="font-size-32rpx leading-38rpx">乐缘币余额 ：</text>
        <text class="font-size-40rpx leading-47rpx">{{ balance || 0 }} 乐缘币</text>
      </view>

      <!-- 套餐列表 -->
      <view class="w-center pt-36rpx flex-sb-center flex-wrap">
        <package-item
          v-for="item in packageInfoList" 
          :key="item.name"
          :data="item"
          :select-package-id="fromData.rechargePackageId"
          @handleClick="handleClickPackage"
        />
        <view class="w-210rpx h-164rpx mb-12rpx"
          v-if="packageInfoList.length % 3 !== 0"
        ></view>
      </view>

      <!-- 自定义金额输入框 -->
      <view class="w-center h-132rpx bg-#FEFAF2 !mt-28rpx flex-sb-center box-border pl-50rpx pr-50rpx"
        :class="[{ 'dark-color2': themeConfig.theme === 'dark' }]"
      >
        <text class="inline-block w-60rpx color-#2E1305 font-size-40rpx leading-28rpx"
          :class="[{ '!color-white': themeConfig.theme === 'dark' }]"
        >￥</text>
        <view class="w-560rpx">
          <wd-input
            label="自定义金额"
            prop="price"
            clearable
            v-model="fromData.amount"
            placeholder="输入自定义金额"
            @input="handleChangeAmount"
            @change="handleChangeAmount"
          />
        </view>
      </view>
      
      <!-- 立即充值 -->
      <view class="btn-full w-center pt-50rpx">
        <wd-button 
          class="btn-w-full btn-h-78"
          @click="confirm"
        >立即充值</wd-button>
      </view>

      <view class="w-full h-50rpx"></view>
      <view class="border-1px"></view>
    </view>

    <view class="w-638rpx m-a pt-74rpx flex-sb-center"
      :class="[{ '!color-white': themeConfig.theme === 'dark' }]"
    >
      <text class="font-size-32rpx leading-38rpx color-#2E1305 font-bold">消费明细</text>
      <wd-drop-menu>
        <wd-drop-menu-item v-model="recordType" :options="enumParams.recordList" @change="handleChange" />
      </wd-drop-menu>
    </view>

    <view class="pb-64rpx">
      <RechargeList v-if="recordType === 0" ref="rechargeListRefs" :userId="user.userInfo.id" />
      <ConsumeList v-else ref="consumeListRefs" :userId="user.userInfo.id" />
    </view>
  </scroll-view>
</template>
  
<script lang="ts" setup>
import PackageItem from "@/components/list-item/package-item.vue";
import RechargeList from "@/components//list-item/recharge-list.vue";
import ConsumeList from "@/components//list-item/consume-list.vue";
import { enumParams } from "@/enum";
import { GetQueryBalance, GetRechargePackageInfoList, UserBalanceInfoAddAmount } from "@/service/db_feature";
import { Feature } from "@/service/types/feature";
import { useCommonStore, useThemeStore, useUserStore } from "@/store";
import { useToast, useQueue } from "wot-design-uni";
import { back, isIOS } from "@/utils";

// 主题颜色
const { themeConfig } = useThemeStore();
const user = useUserStore();
const toast = useToast();
const common = useCommonStore();
const { closeOutside } = useQueue();

const recordType = ref<number>(0)
function handleChange({ value }) {
  reLoadRecord();
}

const fromData = reactive({
  userId: user.userInfo.id,
  amount: '',
  rechargePackageId: ''
})

// const {
//   list, 
//   status,
//   pagination,
//   getList,
//   reLoadList
// } = useList({
//   getApi: UserRechargeRecordInfoPage,
//   _query: {
//     pageSize: 20,
//   },
//   setParams: () => {
//     pagination.userId = fromData.userId;
//   },
// });

// 确认充值弹窗
const confirm = async () => {
  if (!fromData.amount) return toast.show('请输入金额!');
  uni.showLoading({
    title: '正在调起支付'
  });
  try {
    const res = await UserBalanceInfoAddAmount(fromData);
    if (res.code != 200) {
      uni.hideLoading();
      return toast.show(res.message);
    }
    payment(res.data);
  } catch (error) {
    console.log(error)
  }
}

// 调起微信支付
const payment = ({
  nonceStr, packageValue, paySign, signType, timeStamp
}) => {
  if (isIOS() && common.chargeConfig.typeName === 'false') {
    uni.showToast({
      title: '由于相关规范，iOS功能暂不可用',
      icon: 'none'
    })
    return 
  }
  wx.requestPayment({
    timeStamp,
    nonceStr,
    package: packageValue,
    signType,
    paySign,
    success: (res) => {
      uni.hideLoading();
      toast.show('充值成功！');
      reLoad();

      setTimeout(() => {
        backType.value == 2 && back();
      }, 1000)
    },
    fail: (err) => {
      uni.hideLoading();
      console.log('fail:' + JSON.stringify(err));
    }
  })
}

const handleClickPackage = (data) => {
  fromData.amount = data.amount || 0;
  fromData.rechargePackageId = data.id;
}

const handleChangeAmount = (val) => {
  const packageInfoItem = packageInfoList.value.find(item => (val.value == item.price));
  fromData.rechargePackageId = packageInfoItem ? packageInfoItem.id : '';
}

const packageInfoList = ref(enumParams.packageList);
// 获取充值套餐
const getRechargePackageInfoList = async () => {
  const res = await GetRechargePackageInfoList({
    id: user.userInfo.id
  });
  reLoad();
  const list = res.data || [];
  packageInfoList.value = list.map(item => {
    return {
      name: item.packageName,
      price: item.amount,
      give: item.bonusAmount,
      ...item
    }
  })
}

const balance = ref<string | number>(0);
// 获取用户乐缘币
const getQueryBalance = async () => {
  const res = await GetQueryBalance({
    userId: user.userInfo.id
  });
  const data = res.data || {} as Feature.QueryBalanceRes;
  balance.value = data.balance || 0;
}

const rechargeListRefs = ref();
const consumeListRefs = ref();
const reLoadRecord = () => {
  setTimeout(() => {
    nextTick(() => {
      if (recordType.value === 0) {
        rechargeListRefs.value.reLoadList();
      } else {
        consumeListRefs.value.reLoadList();
      }
    })
  }, 200)
}

const reLoad = () => {
  reLoadRecord();
  getQueryBalance();
}

// 底部上拉加载
const onRefresh = () => {
  nextTick(() => {
    if (recordType.value === 0) {
      rechargeListRefs.value.getList();
    } else {
      consumeListRefs.value.getList();
    }
  })
}

const backType = ref(1);
onLoad((options) => {
  const { type } = options || {};
  backType.value = type || 1;
})

onShow(() => {
  nextTick(() => {
    // 设置页面标题
    themeConfig.title = '充值';
  })
  getRechargePackageInfoList();
})
</script>

<script lang="ts">
export default {
  // 微信小程序开启样式穿透
  options: { styleIsolation: "shared" },
};
</script>

<style lang="scss" scoped>
:deep(.wd-input__label) {
  display: none !important;
}

.recharge-container {
  :deep(.wd-input) {
    padding-left: 0 !important;
    padding-right: 0 !important;
    background-color: #FEFAF2 !important;
  }
}

.recharge-dark-bg {
  :deep(.wd-input) {
    background-color: #141414 !important;
  }
}
</style>
  